package com.googlecode.grt192.HH11.mechanism;

import com.googlecode.grt192.HH11.actuator.ISolenoid;
import com.googlecode.grt192.HH11.event.SafetyEvent;
import com.googlecode.grt192.HH11.event.SafetyListener;
import com.googlecode.grt192.HH11.sensor.HHSafety;

/**
 * A Haunted House Mechanism can either contract or retract, with safety
 * 
 * @author ajc
 * 
 */
public class HHMechanism implements SafetyListener {

	private ISolenoid[] solenoids;

	private boolean stopped;

	private final HHSafety sswitch;

	// TODO establish a default state (contracted or retracted)
	// TODO implement default state in solenoid
	public HHMechanism(ISolenoid[] sol, HHSafety sswitch) {
		this.solenoids = sol;
		this.sswitch = sswitch;
		stopped = false; // we start assuming things are safe
	}

	/**
	 * Commands Mechanism pneumatic actuator to reach to a resting state
	 */
	public void contract() {
		if (!stopped) {// only actuate if we are not stopped
			for (ISolenoid sol : solenoids) {// actuate all actuators
				sol.deactivate();
			}
		}
	}

	/**
	 * Commands Mechanism pneumatic actuator to reach the energized state
	 */
	public void retract() {
		if (!stopped) {// only actuate if we are not stopped
			for (ISolenoid sol : solenoids) {// actuate all actuators
				sol.activate();
			}
		}
	}

	@Override
	public void halt(SafetyEvent se) {
		contract();
		stopped = true;
	}

	@Override
	public void suspend(SafetyEvent se) {
		stopped = true;
	}

	public void resume(SafetyEvent se) {
		stopped = false;
	}

	@Override
	public void startListening() {
		sswitch.addSafetyListener(this);
	}

	@Override
	public void stopListening() {
		sswitch.removeSafetyListener(this);
	}

}
